package com.gdcp.controller.portal;

import com.gdcp.beans.News;
import com.gdcp.config.RequestHolder;
import com.gdcp.config.annotation.CategoryByAll;
import com.gdcp.service.NewsService;
import com.gdcp.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */

@Controller
@RequestMapping("/render/news/")
public class NewsController {

    @Autowired
    NewsService newsService;

    @RequestMapping(value = "/queryNewsByNewsId")
    @CategoryByAll(flush = true)
    public String queryShopByShopId(String news_id){
        HttpServletRequest request=RequestHolder.getRequest();

        if (news_id==null||news_id.equals("")){
            return "error";
        }

        Integer newsId= Integer.valueOf(news_id);
        News news=newsService.getInformation(newsId);

        newsService.updateLooks(newsId);
        request.setAttribute("news",news);
        request.setAttribute("content", FileUtil.readWord(news.getContent_url()));
        return "frontend/news";
    }

    /**
     * 得到网页中图片的地址
     */
    public Set<String> getImgStr(String htmlStr) {
        Set<String> pics = new HashSet<String>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }
}
